package com.ruoyi.system.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.Ship;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.CarShip;
import com.ruoyi.system.service.ICarShipService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * 车船调度Controller
 * 
 * @author ruoyi
 * @date 2024-10-18
 */
@RestController
@RequestMapping("/system/CarShip")
public class CarShipController extends BaseController
{
    @Autowired
    private ICarShipService carShipService;
    // 使用 RestTemplate 调用外部API
    private RestTemplate restTemplate = new RestTemplate();

    @PreAuthorize("@ss.hasPermi('system:CarShip:query')")
    @GetMapping("/singleCarShip/{shipID}")
    public AjaxResult querySingleCarShip(@PathVariable("shipID") Long shipID) {
        String apiUrl = UriComponentsBuilder.fromHttpUrl("http://api.shipxy.com/apicall/GetSingleShip")
                .queryParam("v", 2)
                .queryParam("k", "922bc1072d5f4543ac8909e6da2206db")
                .queryParam("enc", 1)
                .queryParam("id", shipID)
                .build()
                .toUriString();

        try {
            String response = restTemplate.getForObject(apiUrl, String.class);

            // 使用 fastjson 解析
            JSONObject jsonObject = JSON.parseObject(response);
            int status = jsonObject.getIntValue("status");
            if (status != 0) {
                return error("API 返回状态码错误: " + status);
            }

            JSONArray shipData = jsonObject.getJSONArray("data");
            JSONObject shipDetail = shipData.getJSONObject(0);

            CarShip carShip = new CarShip();
            carShip.setShipID(shipDetail.getLong("ShipID"));
            carShip.setMmsi(shipDetail.getLong("mmsi"));
            carShip.setShiptype(shipDetail.getLong("shiptype"));
            carShip.setImo(shipDetail.getLong("imo"));
            carShip.setName(shipDetail.getString("name"));
            carShip.setCallsign(shipDetail.getString("callsign"));
            carShip.setLength(shipDetail.getLong("length"));
            carShip.setWidth(shipDetail.getLong("width"));
            carShip.setLeft(shipDetail.getLong("left"));
            carShip.setTrail(shipDetail.getLong("trail"));
            carShip.setDraught(shipDetail.getLong("draught"));
            carShip.setDest(shipDetail.getString("dest"));
            carShip.setDestStd(shipDetail.getString("dest_std"));
            carShip.setDestcode(shipDetail.getString("destcode"));
            carShip.setEta(StringUtils.isBlank(shipDetail.getString("eta_std")) ? null : DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", shipDetail.getString("eta_std")));
            carShip.setNavistat(shipDetail.getLong("navistat"));
            carShip.setLat(shipDetail.getLong("lat"));
            carShip.setLon(shipDetail.getLong("lon"));
            carShip.setSog(shipDetail.getLong("sog"));
            carShip.setCog(shipDetail.getLong("cog"));
            carShip.setHdg(shipDetail.getLong("hdg"));
            carShip.setRot(shipDetail.getLong("rot"));
            carShip.setLasttime(shipDetail.getLong("lasttime"));

            // 保存到数据库
            carShipService.insertCarShip(carShip);

            // 返回成功响应
            return AjaxResult.success("船舶信息已保存", carShip);

        } catch (Exception e) {
            e.printStackTrace();
            return error("API 调用失败: " + e.getMessage());
        }
    }
    /**
     * 查询车船调度列表
     */
    @PreAuthorize("@ss.hasPermi('system:CarShip:list')")
    @GetMapping("/list")
    public TableDataInfo list(CarShip carShip)
    {
        startPage();
        List<CarShip> list = carShipService.selectCarShipList(carShip);
        return getDataTable(list);
    }

    /**
     * 导出车船调度列表
     */
    @PreAuthorize("@ss.hasPermi('system:CarShip:export')")
    @Log(title = "车船调度", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CarShip carShip)
    {
        List<CarShip> list = carShipService.selectCarShipList(carShip);
        ExcelUtil<CarShip> util = new ExcelUtil<CarShip>(CarShip.class);
        util.exportExcel(response, list, "车船调度数据");
    }

    /**
     * 获取车船调度详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:CarShip:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(carShipService.selectCarShipById(id));
    }

    /**
     * 新增车船调度
     */
    @PreAuthorize("@ss.hasPermi('system:CarShip:add')")
    @Log(title = "车船调度", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CarShip carShip)
    {
        return toAjax(carShipService.insertCarShip(carShip));
    }

    /**
     * 修改车船调度
     */
    @PreAuthorize("@ss.hasPermi('system:CarShip:edit')")
    @Log(title = "车船调度", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CarShip carShip)
    {
        return toAjax(carShipService.updateCarShip(carShip));
    }

    /**
     * 删除车船调度
     */
    @PreAuthorize("@ss.hasPermi('system:CarShip:remove')")
    @Log(title = "车船调度", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(carShipService.deleteCarShipByIds(ids));
    }
}
